﻿using System;
using System.Windows.Forms;
using PersonalAccoutingProgram.Data;

public partial class LoginForm : Form
{ 
    private const string SUCCESSFULL_ADDED_USER_MSG = 
    "New user added successfully!";

    public User user { get; private set; }
 
    public LoginForm()
    {
        InitializeComponent();
        user = new User();
    }
     
    private void buttonLogIn_Click(object sender, EventArgs e)
    {
        try
        {
            if (DataValidator.isUserInformationCorrect(
                textBoxUserName.Text, tbPassword.Text))
            {
                user.Username = textBoxUserName.Text;
                user.Password = tbPassword.Text;
                this.DialogResult = DialogResult.OK;
                MainMenu menu = new MainMenu(user.Username);
                textBoxUserName.Text = String.Empty;
                tbPassword.Text = String.Empty;
                menu.ShowDialog();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void LoginForm_Load(object sender, EventArgs e)
    {
    }

    private void buttonCancel_Click(object sender, EventArgs e)
    {
        this.Dispose();
    }

    private void btnRegistration_Click(object sender, EventArgs e)
    {
        try
        {
            bool isValid = DataValidator.isUserInputValid(
                textBoxUserName.Text, tbPassword.Text);
            if (isValid)
            {
                UserDataClassesDataContext.RegisterNewUser(
                    textBoxUserName.Text, tbPassword.Text);
                MessageBox.Show(SUCCESSFULL_ADDED_USER_MSG);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void LoginForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (MessageBox.Show("Are you sure that you want to quit?", "Closing", 
                            MessageBoxButtons.YesNo) == DialogResult.No)
        {
            e.Cancel = true;
        }
    }

    private void tbPassword_KeyPress(object sender, KeyPressEventArgs e)
    {
        DataValidator.ValidatePassword(e);
    }

    private void textBoxUserName_KeyPress(object sender, KeyPressEventArgs e)
    {
        DataValidator.ValidateUsername(e);
    }
}